package com.ff.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ff.common.BaseContext;
import com.ff.common.R;
import com.ff.entity.ShoppingCart;
import com.ff.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    //添加购物车
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //设置用户id
        shoppingCart.setUserId(BaseContext.getThreadContext());


        Long dishId = shoppingCart.getDishId();

        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        if (dishId!=null){
            queryWrapper.eq("dish_id",dishId);
        }else {
            queryWrapper.eq("setmeal_id",shoppingCart.getSetmealId());
        }

        ShoppingCart shoppingCart1 = shoppingCartService.getOne(queryWrapper);
        //查询菜品或套餐是否在购物车中
        if (shoppingCart1==null){
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        }else {
            shoppingCart.setId(shoppingCart1.getId());
            shoppingCart.setNumber(shoppingCart1.getNumber()+1);
            shoppingCartService.updateById(shoppingCart);
        }
        return R.success(shoppingCart);
    }

    //查看购物车
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",BaseContext.getThreadContext());
        queryWrapper.orderByAsc("create_time");
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return R.success(list);
    }
    //清空购物车
    @DeleteMapping("/clean")
    public R<String> clean(){
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",BaseContext.getThreadContext());
        shoppingCartService.remove(queryWrapper);

        return R.success("清空购物车成功");
    }
}
